import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/base/base_refresh_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_main_list_entity.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:get/get.dart';

import 'drama_category_state.dart';

class DramaCategoryController extends BaseRefreshController {
  DramaCategoryController({this.categoryId = 0});

  final DramaCategoryState state = DramaCategoryState();

  final int categoryId;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  @override
  fetchData({bool showLoading = true}) async {
    // 开始加载
    if (showLoading) {
      loadStatus = 0;
      update();
    }

    try {
      // 加载好剧
      state.mainList = await _loadMainListData(1);

      if (showLoading) {
        loadStatus = state.mainList.isNotEmpty ? 1 : 2;
      }
    } catch (e) {
      if (showLoading) {
        loadStatus = 3;
      } else {
        EasyLoading.showError('加载失败');
      }
    }
    update();
    // 结束下拉
    state.currentPage = 1;
    refreshController.refreshCompleted(resetFooterState: true);
  }

  @override
  onLoadMore() async {
    try {
      var list = await _loadMainListData(state.currentPage + 1);
      if (list.length < GlobalConfig.waterfallPageSize) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
      state.currentPage += 1;
      state.mainList.addAll(list);

      update();
    } catch (e) {
      refreshController.loadFailed();
    }
  }

  /// 获取主列表
  Future<List<DramaMainListEntity>> _loadMainListData(int page) async {
    List<DramaMainListEntity> list = [];
    try {
      var result = await DramaDao.getDramaMainList(
        categoryId == 0 ? null : categoryId,
        pageIndex: page,
        pageSize: GlobalConfig.waterfallPageSize,
      );
      if (result.code == 0) {
        // 成功
        if (result.data != null) {
          list = result.data!;
          // 随机类别
          if (GlobalConfig.isReview == 1) {
            list.shuffle();
          }
        }
      }
    } catch (_) {}
    return list;
  }
}
